# -*- coding: utf-8 -*-
import os

import requests
import sys
from lxml import etree


class Trans(object):
    def __init__(self, word):
        self.url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
        self.post_data = {
            'i': word,
            'from': 'AUTO',
            'to': 'AUTO',
            'smartresult': 'dict',
            'client': 'fanyideskweb',
            'salt': '',
            'sign': '',
            'ts': '',
            'bv': '',
            'doctype': 'json',
            'version': '2.1',
            'keyfrom': 'fanyi.web',
            'action': 'FY_BY_CLICKBUTTION',
            'typoResult': 'false'
        }

        _path = os.path.join(os.path.abspath('.'), '../')
        sys.path.append(_path)
        self.ei = __import__('Utils.C002_extract_info', fromlist=['C002_extract_info'])
        self.ua_file = {'pc': '{0}Utils/{1}'.format(_path, self.ei.ExtractInfo.ua_file['pc'])}

    def get_data(self):
        _user_agent = self.ei.ExtractInfo.get_useragent(file=self.ua_file)
        # TODO 处理加密函数
        response = requests.post(self.url, headers=_user_agent, data=self.post_data)

        return response.content.decode()

    def parse_data(self, data):
        print(data)
        _html = etree.HTML(data)
        print(_html)

    def run(self):
        _data = self.get_data()
        self.parse_data(_data)


def main():
    word = input('请输入查询的单词: ')
    trans = Trans(word)
    trans.run()


if __name__ == '__main__':
    main()
